package com.issoft.studentresitor.service.impl;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.issoft.studentresitor.domain.pojo.Fee;
import com.issoft.studentresitor.domain.pojo.Feitem;
import com.issoft.studentresitor.domain.pojo.Result;
import com.issoft.studentresitor.domain.pojo.Student;
import com.issoft.studentresitor.domain.query.FeeQuery;
import com.issoft.studentresitor.domain.vo.FeeVo;
import com.issoft.studentresitor.mapper.FeeMapper;
import com.issoft.studentresitor.mapper.FeitemMapper;
import com.issoft.studentresitor.mapper.StudentMapper;
import com.issoft.studentresitor.service.IFeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.issoft.studentresitor.utils.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author GJH
 * @since 2025-09-14
 */
@Slf4j
@Service
public class FeeServiceImpl extends ServiceImpl<FeeMapper, Fee> implements IFeeService {
    @Autowired
    private FeeMapper feeMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private FeitemMapper feitemMapper;
    @Override
    public PageResult<FeeVo> queryFeePage(FeeQuery feeQuery) {
        log.info("分页查询缴费记录，参数：{}", feeQuery);
        PageHelper.startPage(feeQuery.getPage(), feeQuery.getPageSize());
        List<FeeVo> feeVos = feeMapper.queryFeePage(feeQuery);
        Page<FeeVo> pageResult = (Page<FeeVo>) feeVos;
        return new PageResult<>(pageResult.getTotal(), pageResult.getResult());
    }
    @Override
    public List<FeeVo> queryFeeByStudentId(String studentId) {
        log.info("根据学生ID查询缴费记录，学生ID：{}", studentId);
        return feeMapper.queryFeeByStudentId(studentId);
    }

    @Override
    @Transactional
    public boolean updatePaymentStatus(Integer feeId, String paymentStatus, String paymentMethod) {
        log.info("更新支付状态，缴费ID：{}，支付状态：{}，支付方式：{}", feeId, paymentStatus, paymentMethod);
        int result = feeMapper.updatePaymentStatus(feeId, paymentStatus, paymentMethod);
        return result > 0;
    }
    @Override
    @Transactional
    public boolean batchCreateFeeItems(List<Fee> fees) {
        log.info("批量创建缴费项目，数量：{}", fees.size());
        try {
            for (Fee fee : fees) {
                fee.setPaymentStatus("未支付");
                feeMapper.insert(fee);
            }
            return true;
        } catch (Exception e) {
            log.error("批量创建缴费项目失败", e);
            return false;
        }
    }

    @Override
    public Result export(HttpServletResponse response, List<Long> ids) throws IOException {
        log.info("导出缴费记录，IDs：{}", ids);

        // 查询数据
        List<Fee> fees = feeMapper.selectBatchIds(ids);

        // 创建Excel写入器
        ExcelWriter excelWriter = ExcelUtil.getWriter(true);
        excelWriter.write(fees, true);

        // 设置响应头
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("缴费记录", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 写入响应
        ServletOutputStream outputStream = response.getOutputStream();
        excelWriter.flush(outputStream, true);
        excelWriter.close();
        outputStream.close();

        return Result.success();
    }

    @Override
    public FeeVo getFeeStatistics() {
        log.info("获取缴费统计信息");
        return feeMapper.getFeeStatistics();
    }

    @Override
    @Transactional
    public boolean batchPay(Integer userId, Integer[] feeItemIds) {
        Student student = studentMapper.selectOne(new QueryWrapper<Student>()
                .eq("user_id", userId));
        String studentId = student != null ? student.getStudentId() : "学生不存在";
        log.info("批量支付，学生ID：{}", studentId);
        // 2. 拿到缴费项目
        List<Feitem> feeIems = feitemMapper.selectBatchIds(Arrays.asList(feeItemIds));
        log.info("批量支付，缴费项目：{}", feeIems);
        if (feeIems != null && !feeIems.isEmpty()) {
            for (Feitem feeItem : feeIems) {
                Fee fee = new Fee();
                fee.setStudentId(studentId);
                fee.setFeeItem(feeItem.getFeeType());
                fee.setFeeAmount(BigDecimal.valueOf(feeItem.getFeeNumber()));
                fee.setPaymentStatus("已支付");
                fee.setPaymentMethod("微信");
                fee.setPaymentDate(LocalDateTime.now());
                feeMapper.insert(fee);
                log.info("批量支付，缴费项目：{}", fee);
            }
            return true;
        }
        return false;
    }

    @Override
    public List<Fee> queryByUserId(Integer userId) {
        return feeMapper.queryByUserId(userId);
    }

}
